'use client';
import { type FC, useEffect, useRef, lazy } from 'react';
import { useSetState } from 'ahooks';
import cookie from 'js-cookie';
import type { MenuProps } from 'antd';
import { Dropdown } from 'antd';
import classNames from 'classnames';
import styles from './index.module.scss';

import Confirm from '@/app/components/Confirm';
import Login from '@/app/components/Login';
import Drawer from '@/app/components/Drawer';
import Templates from '../templates';
// import { exportAndDownloadByBuffer } from '@/utils';
import { checkVipInfo, downloadFile } from '@/service';
import { getStyle } from '@/app/utils';
import { usePersonalDetailStore } from '@/src/providers/personal-detail-store-provider';
import { useCustomizationStore } from '@/src/providers/customization-store-provider';
import { useCommonStore } from '@/src/providers/common-store-provider';
import Spacing from '../customization/spacing';
import HeaderSpacing from '../customization/header/spacing';
import ModuleSpacing from '../customization/module/spacing';
import Colors from '../customization/colors';
import TitleBkgColor from '../customization/module/title/titleBkgColor';
import { exportAndDownloadByBuffer } from '@/util';
import Vip from '../../vip';
const Customization = lazy(async () => {
  return import('../customization');
});
interface IndexProps {
  current?: string;
  style?: React.CSSProperties;
}

const Index: FC<IndexProps> = ({ current, style }) => {
  const [state, setState] = useSetState({
    scrollTop: 0,
    showDropDown: false,
    showDrawer: false,
    editItem: null,
    showVip: false,
  });
  const scrollTopRef = useRef(0);
  const {
    isLogin,
    showLogin,
    currentTab,
    setShowLogin,
    setIsLogin,
    isMobile,
    htmlString,
    setDownloading,
  } = useCommonStore((state) => state);
  const { personalDetails } = usePersonalDetailStore((state) => state);
  const { customization } = useCustomizationStore((state) => state);

  const scroll = () => {
    if (window.scrollY > 0 && scrollTopRef.current === 0) {
      scrollTopRef.current = window.scrollY;
      setState({
        scrollTop: window.scrollY,
      });
    }
    if (window.scrollY === 0) {
      scrollTopRef.current = window.scrollY;
      setState({
        scrollTop: window.scrollY,
      });
    }
  };
  useEffect(() => {
    window.addEventListener('scroll', scroll);
    return () => {
      window.removeEventListener('scroll', scroll);
    };
  }, []);
  const items: MenuProps['items'] = [
    {
      key: '1',
      label: (
        <div
          onClick={() => {
            window.open('/my');
          }}
        >
          我的账户
        </div>
      ),
    },
    {
      key: '2',
      label: (
        <div
          onClick={() => {
            window.open('/my/cv');
          }}
        >
          我的简历
        </div>
      ),
    },
    {
      key: '3',
      label: (
        <div
          onClick={() => {
            Confirm({
              content: '确认退出？',
              onOk: async () => {
                cookie.remove('baijie_token');
                setIsLogin(false);
              },
            });
          }}
        >
          退出登录
        </div>
      ),
    },
  ];
  return (
    <>
      {!isMobile ? (
        <div
          className={classNames(
            styles.header,
            state.scrollTop > 0 ? styles.shadow : '',
          )}
          style={style}
        >
          <div className={styles.content}>
            <a className={styles.logo} target="_blank" href="/">
              百捷简历
            </a>

            <div className={classNames(styles.menus, styles.hide)}>
              <a
                className={classNames(
                  styles.menu,
                  current === 'fanwen' ? styles.active : '',
                )}
                onClick={() => {
                  setState({
                    showDrawer: true,
                    editItem: 'temp',
                  });
                }}
              >
                更换模板
              </a>
              <a
                className={classNames(
                  styles.menu,
                  current === 'fanwen' ? styles.active : '',
                )}
                onClick={() => {
                  setState({
                    showDrawer: true,
                    editItem: 'space',
                  });
                }}
              >
                间距设置
              </a>
              <a
                className={classNames(
                  styles.menu,
                  current === 'fanwen' ? styles.active : '',
                )}
                onClick={() => {
                  setState({
                    showDrawer: true,
                    editItem: 'color',
                  });
                }}
              >
                颜色设置
              </a>

              <a
                className={classNames(
                  styles.menu,
                  current === 'fanwen' ? styles.active : '',
                )}
                onClick={() => {
                  setState({
                    showDrawer: true,
                    editItem: 'more',
                  });
                  // setCurrentTab("customize");
                }}
              >
                更多设置
              </a>
              <a
                className={classNames(
                  styles.menu,
                  current === 'fanwen' ? styles.active : '',
                  styles.solid,
                )}
                onClick={async () => {
                  if (currentTab !== 'content') {
                    Confirm({
                      content: '请先保存简历，再进行导出',
                      cancelButtonProps: {
                        style: {
                          display: 'none',
                        },
                      },
                      cancelText: '取消',
                    });
                    return;
                  }
                  if (isLogin) {
                    let res = await checkVipInfo();
                    console.log(res);
                    if (!res.data) {
                      setState({
                        showVip: true,
                      });
                      return;
                    }
                  }
                  try {
                    setDownloading(true);
                    try {
                      let res = await exportAndDownloadByBuffer(
                        downloadFile({
                          htmlString: getStyle() + htmlString,
                          fileName: `${personalDetails.name}_${
                            personalDetails.expJob || ''
                          }`,
                          templateId: customization.templateId || null,
                          resumeId: personalDetails.id || null,
                        }),
                      );
                      setDownloading(false);
                      if (!res) return;
                      Confirm({
                        content: '简历下载完成，请至电脑中查看！',
                        showCancelButton: false,
                        cancelButtonProps: {
                          style: {
                            display: 'none',
                          },
                        },
                      });
                    } catch (e) {
                      console.log(e);
                    }

                    setDownloading(false);
                  } catch (e) {}
                }}
              >
                下载简历
              </a>
            </div>
            <div className={styles.loginArea}>
              {isLogin ? (
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <div onClick={() => {}}>
                    <Dropdown menu={{ items }} placement="bottomRight">
                      <div
                        style={{
                          fontSize: '14px',
                          cursor: 'pointer',
                          display: 'flex',
                          alignItems: 'center',
                        }}
                      >
                        <div
                          style={{
                            width: '30px',
                            height: '30px',
                            borderRadius: '50%',
                            background: '#5659fe',
                            marginRight: '10px',
                            display: 'flex',
                            justifyContent: 'center',
                            alignItems: 'center',
                            color: '#fff',
                          }}
                        >
                          S
                        </div>{' '}
                        个人中心
                      </div>
                    </Dropdown>
                  </div>
                </div>
              ) : (
                <div
                  className={styles.loginBtn}
                  onClick={() => {
                    setShowLogin(true);
                  }}
                >
                  登录 / 注册
                </div>
              )}
            </div>
            {/* // )} */}
          </div>
        </div>
      ) : null}
      <Drawer
        visible={state.showDrawer}
        width={600}
        onClose={() => {
          setState({
            showDrawer: false,
            editItem: null,
          });
        }}
      >
        {state.editItem === 'temp' ? <Templates /> : null}
        {state.editItem === 'space' ? (
          <>
            <Spacing onlySpace />
            <div style={{ marginTop: 50, padding: '0 20px' }}>
              <HeaderSpacing />
            </div>
            <div style={{ marginTop: 50, padding: '0 20px' }}>
              <ModuleSpacing />
            </div>
          </>
        ) : null}
        {state.editItem === 'color' ? (
          <>
            <Colors />
            <div style={{ marginTop: '40px', padding: '0 20px' }}>
              <TitleBkgColor />
            </div>
          </>
        ) : null}
        {state.editItem === 'more' ? (
          <Customization hasNoTemp></Customization>
        ) : null}
      </Drawer>
      {showLogin ? <Login></Login> : null}
      {state.showVip ? (
        <Vip
          onClose={() => {
            setState({ showVip: false });
          }}
        ></Vip>
      ) : null}
    </>
  );
};

export default Index;
